﻿using LJ.Host.Abstractions.DependencyInjection;
using LJ.Host.Abstractions.Pack.Internal;
using LJ.Host.Abstractions.Pack;
using LJ.Host.Abstractions.Thread;
using LJ.Host.Web.Pack.Internal;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LJ.Host.Worker.Pack;

namespace LJ.Host.Worker.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddLJ(this IServiceCollection serviceCollection, IConfiguration configuration)
    {

        serviceCollection.AddSingleton<PackBootstrapper>();

        serviceCollection.AddTransient<ICancellationTokenProvider, CancellationTokenProvider>();

        serviceCollection.AddTransient<IConfigProvider, ConfigProvider>();

        var packContext = new PackContext(serviceCollection, configuration);

        var packManager = new PackManager(packContext.ReflectionManager);
        serviceCollection.AddSingleton<IPackManager>(packManager);

        //Startup and Hosted 
        var packProcessingServerManager = new PackServerManager(packContext.DependencyManager, packContext.ReflectionManager);
        serviceCollection.AddSingleton<IPackServerManager>(packProcessingServerManager);

        serviceCollection.AddSingleton<IPackLifetime, PackLifetime>();

        serviceCollection.AddSingleton<PackBootstrapper>();
        serviceCollection.AddHostedService(sp => sp.GetRequiredService<PackBootstrapper>());
        serviceCollection.AddSingleton<IPackBootstrapper>(sp => sp.GetRequiredService<PackBootstrapper>());


        serviceCollection.AddSingleton<IDependencyInjectionFactory, DependencyInjectionFactory>();

        serviceCollection.AddSingleton<IHybridProvider<IServiceProvider>, HybridProvider<IServiceProvider>>();
        serviceCollection.AddTransient<IHybridProviderHandler<IServiceProvider>, HybridProviderHandler<IServiceProvider>>();

        serviceCollection.AddSingleton<IHybridProvider<CancellationToken>, HybridProvider<CancellationToken>>();
        serviceCollection.AddTransient<IHybridProviderHandler<CancellationToken>, HybridProviderHandler<CancellationToken>>();


        foreach (var pack in packManager.GetPacks())
        {
            pack.Add(packContext);
        }
        return serviceCollection;
    }
}
